<template>
  <div>
    <!-- 头部 -->
    <van-nav-bar title="黑马油条-登录"/>
    <van-form @submit="onSubmit">
      <van-field
        v-model="formItem.mobile"
        required
         name="用户名"
        label="手机号码"
        placeholder="请输入手机号"
        :rules="[{ required: true,
         message: '请输入正确的手机号',
         trigger:'onchange',
         pattern:/^1[3-9]\d{0,9}$/}]"
      />
      <van-field
        v-model="formItem.code"
        required
        type="password"
        name="密码"
        label="登录密码"
        placeholder="请输入密码"
        :rules="[{ required: true, message: '请填写密码', trigger:'onchange', pattern:/^\d{6}$/}]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit" :loading='isLoading' loading-text="王亚飞快跑..." :disabled='isLoading'>登录</van-button>
      </div>
   </van-form>
  </div>
</template>

<script>
// 按需导入
import { loginAPI } from '@/api'
import { Notify } from 'vant'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data () {
    return {
      formItem: {
        mobile: '13800006666',
        code: '246810'// 后台用
      },
      isLoading: false // 按钮加载状态
    }
  },
  methods: {
    // 点击登录
    // 原地展开vuex映射过来的方法
    ...mapMutations(['setToken', 'setRefreshToken']),
    async onSubmit () {
      try {
        // 按钮状态一开始 true
        this.isLoading = true
        const res = await loginAPI(this.formItem)
        // 获取token,refresh_token
        const { token, refresh_token } = res.data.data
        // 调用vuex映射过来的方法
        this.setToken(token)
        this.setRefreshToken(refresh_token)
        console.log(res)
        // 登录完成后恢复按钮状态
        this.isLoading = false
        Notify({ type: 'success', message: '出来吧,王亚飞' })
        // 跳转到layout页面
        this.$router.push({
          path: '/layout'
        })
      } catch (error) {
        // 如果登录失败也得恢复按钮状态
        this.isLoading = false
        Notify({ type: 'danger', message: '翻滚吧,王亚飞' })
      }
    }
  }
}
</script>

<style lang="less" scoped>
// .van-nav-bar{
//   background-color: #007bff;
//   // 知识点1:组件内的标签不会被scoped影响添加data-v属性
//   /deep/ .van-nav-bar__title{ // 选择组件内的标签,要用/deep/+空格+后代选择器
//     color: white;
//   }
// }
</style>
